const style = `
    .toast {
        position: fixed;
        left: 50%;
        top: -50px;
        transform: translateX(-50%);
        padding: 10px 20px;
        background-color: rgba(0, 0, 0, 0.6);
        color: #fff;
        border-radius: 5px;
        z-index: 2000;
        transition: all 0.3s;
        animation: show 0.2s linear forwards;
    }
    
    .toast-show {
        opacity: 1;
    }
    
    .toast-hide {
        opacity: 0;
    }
    
    .toast span {
        display: inline-block;
        vertical-align: middle;
    }
    
    @keyframes show {
        0% {
            top: -50px;
        }
        100% {
            top: 30px;
        }
    }
`

/**
 * Toast 提示框
 * @param {Object | String} options
 * @param {String} options.message 提示信息
 * @param {Number} options.duration 持续时间
 * @example
 * Toast({
 *    message: '提示信息',
 *    duration: 1000
 *  });
 */
function Toast(options) {
    let message, duration = 10000;

    // 如果 options 为字符串，则直接赋值给 message
    if (typeof options === 'string') {
        message = options;
    } else {
        message = options.message;
        duration = options?.duration || 3000;
    }

    const toast = document.createElement('div');
    toast.className = 'toast';
    toast.style.zIndex = '2002';
    const text = document.createElement('span');
    text.textContent = message;

    // 添加样式
    const styleTag = document.createElement('style');
    styleTag.textContent = style;
    document.head.appendChild(styleTag);

    // 添加动画
    toast.classList.add('toast-show');

    // 添加元素
    toast.appendChild(text);
    document.body.appendChild(toast);

    // 默认 3s 后隐藏
    setTimeout(() => {
        toast.classList.remove('toast-show');
        toast.classList.add('toast-hide');
        document.body.removeChild(toast);
        document.head.removeChild(styleTag);
    }, duration);
}

